﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Web.DynamicData;
using System.Globalization;
using NotAClue.ComponentModel.DataAnnotations;
using NotAClue.Web.DynamicData;

namespace DD_Extensions.DynamicData.FieldTemplates
{
    public partial class Date_EditField : System.Web.DynamicData.FieldTemplateUserControl
    {
        private String DATE_FORMAT = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;

        protected void Page_Init(object sender, EventArgs e)
        {
            // add tool-tip
            this.SetupTip();

            // set field options
            this.SetFieldOptions();

            // add CSS from meta data
            this.ApplyCss();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1_CalendarExtender.Format = DATE_FORMAT;
            TextBox1.ToolTip = Column.Description;
            TextBox1.Columns = DateTime.Now.ToString(DATE_FORMAT).Length;

            SetUpValidator(RequiredFieldValidator1);
            SetUpValidator(RegularExpressionValidator1);
            SetUpValidator(DynamicValidator1);

            // set validators to use image as error indicator
            this.SetValidatorsToImage();

            // check to see if column is read only in insert mode
            Column.DisableFieldTemplate(Mode, TextBox1);
        }

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);
            // Get attribute
            var autoGenerateDate = Column.GetAttribute<AutoGenerateDateAttribute>();

            // enable disable edit of field
            if (autoGenerateDate != null)
                TextBox1.Enabled = !autoGenerateDate.DisableEdit;

            // set date in insert mode if auto generate is not null
            if (Mode == DataBoundControlMode.Insert && autoGenerateDate != null)
                TextBox1.Text = DateTime.Now.ToString(DATE_FORMAT);

            if (Mode == DataBoundControlMode.Edit)
                TextBox1.Text = FieldValueString;
        }

        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text);
        }

        public override Control DataControl
        {
            get { return TextBox1; }
        }
    }
}
